﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;

namespace george.Web.Helper {
    /// <summary>
    /// 读取请求参数的简单方法
    /// </summary>
    public static class RequestHelper {
        
        /// <summary>
        /// 获取客户端IP地址
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static string GetClientIpAddress(this HttpRequest request) {
            var ip = getClientIpAddress(request.ServerVariables);
            if (string.IsNullOrWhiteSpace(ip)) {
                ip = request.UserHostAddress;
            }
            return ip;
        }
        public static IPAddress GetClientIp(this HttpRequest request) {
            var ip = getClientIpAddress(request.ServerVariables);
            if (string.IsNullOrWhiteSpace(ip)) {
                ip = request.UserHostAddress;
            }
            return IPAddress.Parse(ip);
        }
        public static string GetClientIpAddress(this HttpRequestBase request) {
            var ip = getClientIpAddress(request.ServerVariables);
            if (string.IsNullOrWhiteSpace(ip)) {
                ip = request.UserHostAddress;
            }
            return ip;
        }

        public static string GetPostContent(this HttpRequestBase request) {
            var length = request.ContentLength;
            var bytes = request.BinaryRead(length);
            return Encoding.UTF8.GetString(bytes);
        }
        public static string GetPostContent(this HttpRequest request) {
            var length = request.ContentLength;
            var bytes = request.BinaryRead(length);
            return Encoding.UTF8.GetString(bytes);
        }

        private static string getClientIpAddress(NameValueCollection serverVariables) {
            var loginip = "";
            //Request.ServerVariables[""]--获取服务变量集合   
            if (serverVariables["REMOTE_ADDR"] != null) {//判断发出请求的远程主机的ip地址是否为空  
                                                         //获取发出请求的远程主机的Ip地址  
                loginip = serverVariables["REMOTE_ADDR"];
            } else if (serverVariables["HTTP_VIA"] != null) {//判断登记用户是否使用设置代理  
                loginip = serverVariables["HTTP_X_FORWARDED_FOR"] ?? string.Empty;
            } else {
                //获取客户端IP  
                loginip = string.Empty;
            }
            return loginip;
        }

        /// <summary>
        /// 读取日期类型参数
        /// </summary>
        /// <param name="request"></param>
        /// <param name="name">名称</param>
        /// <param name="dv">默认值</param>
        /// <param name="method">请求方法</param>
        /// <returns></returns>
        public static DateTime Get(this HttpRequestBase request, string name, DateTime dv, HttpVerbs method = HttpVerbs.Anyone) {
            string value = _getValue(request, name, method);
            if (string.IsNullOrEmpty(value)) {
                return dv;
            }
            DateTime.TryParse(value, out dv);
            return dv;
        }
        /// <summary>
        /// 读取日期类型参数
        /// </summary>
        /// <param name="request"></param>
        /// <param name="name">名称</param>
        /// <param name="dv">默认值</param>
        /// <param name="method">请求方法</param>
        /// <returns></returns>
        public static DateTime Get(this HttpRequest request, string name, DateTime dv, HttpVerbs method = HttpVerbs.Anyone) {
            string value = _getValue(request, name, method);
            if (string.IsNullOrEmpty(value)) {
                return dv;
            }
            DateTime.TryParse(value, out dv);
            return dv;
        }
        /// <summary>
        /// 读取字符串
        /// </summary>
        /// <param name="request"></param>
        /// <param name="name"></param>
        /// <param name="dv"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public static string Get(this HttpRequestBase request, string name, string dv, HttpVerbs method = HttpVerbs.Anyone) {
            string value = _getValue(request, name, method);
            if (string.IsNullOrEmpty(value)) {
                return dv;
            }
            return value;
        }
        /// <summary>
        /// 读取字符串
        /// </summary>
        /// <param name="request"></param>
        /// <param name="name"></param>
        /// <param name="dv"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public static string Get(this HttpRequest request, string name, string dv, HttpVerbs method = HttpVerbs.Anyone) {
            string value = _getValue(request, name, method);
            if (string.IsNullOrEmpty(value)) {
                return dv;
            }
            return value;
        }
        /// <summary>
        /// 读取整型
        /// </summary>
        /// <param name="request"></param>
        /// <param name="name"></param>
        /// <param name="dv"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public static int Get(this HttpRequestBase request, string name, int dv, HttpVerbs method = HttpVerbs.Anyone) {
            string value = _getValue(request, name, method);
            if (string.IsNullOrEmpty(value)) {
                return dv;
            }
            int.TryParse(value, out dv);
            return dv;
        }
        /// <summary>
        /// 读取整型
        /// </summary>
        /// <param name="request"></param>
        /// <param name="name"></param>
        /// <param name="dv"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public static int Get(this HttpRequest request, string name, int dv, HttpVerbs method = HttpVerbs.Anyone) {
            string value = _getValue(request, name, method);
            if (string.IsNullOrEmpty(value)) {
                return dv;
            }
            int.TryParse(value, out dv);
            return dv;
        }
        /// <summary>
        /// 读取GUID值，失败返回Guid.Empty
        /// </summary>
        /// <param name="request"></param>
        /// <param name="name"></param>
        /// <param name="method"></param>
        /// <returns>失败返回Guid.Empty</returns>
        public static Guid GetGuid(this HttpRequestBase request, string name, HttpVerbs method = HttpVerbs.Anyone) {
            string value = _getValue(request, name, method);
            if (!string.IsNullOrEmpty(value)) {
                try {
                    return new Guid(value);
                } catch {
                    return Guid.Empty;
                }
            }
            return Guid.Empty;
        }
        /// <summary>
        /// 读取GUID值，失败返回Guid.Empty
        /// </summary>
        /// <param name="request"></param>
        /// <param name="name"></param>
        /// <param name="method"></param>
        /// <returns>失败返回Guid.Empty</returns>
        public static Guid GetGuid(this HttpRequest request, string name, HttpVerbs method = HttpVerbs.Anyone) {
            string value = _getValue(request, name, method);
            if (!string.IsNullOrEmpty(value)) {
                try {
                    return new Guid(value);
                } catch {
                    return Guid.Empty;
                }
            }
            return Guid.Empty;
        }
        /// <summary>
        /// 从Request读取bool值
        /// </summary>
        /// <param name="request"></param>
        /// <param name="name"></param>
        /// <param name="dv"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public static bool Get(this HttpRequestBase request, string name, bool dv, HttpVerbs method = HttpVerbs.Anyone) {
            string value = _getValue(request, name, method);
            if (string.IsNullOrEmpty(value)) {
                return dv;
            }
            bool.TryParse(value, out dv);
            return dv;
        }
        /// <summary>
        /// 是否存在
        /// </summary>
        /// <param name="request"></param>
        /// <param name="name"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public static bool HasKey(this HttpRequestBase request, string name, HttpVerbs method = HttpVerbs.Anyone) {
            switch (method) {
                case HttpVerbs.GET:
                    return request.QueryString.AllKeys.Contains(name);
                case HttpVerbs.POST:
                    return request.Form.AllKeys.Contains(name);
                case HttpVerbs.Anyone:
                default:
                    return string.IsNullOrWhiteSpace(request[name]) == false;
            }
        }
        /// <summary>
        /// 是否存在
        /// </summary>
        /// <param name="request"></param>
        /// <param name="name"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public static bool HasKey(this HttpRequest request, string name, HttpVerbs method = HttpVerbs.Anyone) {
            switch (method) {
                case HttpVerbs.GET:
                    return request.QueryString.AllKeys.Contains(name);
                case HttpVerbs.POST:
                    return request.Form.AllKeys.Contains(name);
                case HttpVerbs.Anyone:
                default:
                    return string.IsNullOrWhiteSpace(request[name]) == false;
            }
        }
        /// <summary>
        /// 从Request读取bool值
        /// </summary>
        /// <param name="request"></param>
        /// <param name="name"></param>
        /// <param name="dv"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public static bool Get(this HttpRequest request, string name, bool dv, HttpVerbs method = HttpVerbs.Anyone) {
            string value = _getValue(request, name, method);
            if (string.IsNullOrEmpty(value)) {
                return dv;
            }
            bool.TryParse(value, out dv);
            return dv;
        }

        private static string _getValue(HttpRequestBase request, string name, HttpVerbs method) {
            string[] values = null;
            switch (method) {
                case HttpVerbs.GET:
                    values = request.QueryString.GetValues(name);
                    break;
                case HttpVerbs.POST:
                    values = request.Form.GetValues(name);
                    break;
                case HttpVerbs.Anyone:
                default: {
                        var v1 = _getValue(request, name, HttpVerbs.POST);
                        if (string.IsNullOrWhiteSpace(v1)) {
                            var v2 = _getValue(request, name, HttpVerbs.GET);
                            return v2;
                        }
                        return v1;
                    }
            }
            if (values != null && values.Length > 0) {
                return values[values.Length - 1];
            } else {
                return string.Empty;
            }
        }
        private static string _getValue(HttpRequest request, string name, HttpVerbs method) {
            string[] values = null;
            switch (method) {
                case HttpVerbs.GET:
                    values = request.QueryString.GetValues(name);
                    break;
                case HttpVerbs.POST:
                    values = request.Form.GetValues(name);
                    break;
                case HttpVerbs.Anyone:
                default: {
                        var v1 = _getValue(request, name, HttpVerbs.POST);
                        if (string.IsNullOrWhiteSpace(v1)) {
                            var v2 = _getValue(request, name, HttpVerbs.GET);
                            return v2;
                        }
                        return v1;
                    }
            }
            if (values != null && values.Length > 0) {
                return values[values.Length - 1];
            } else {
                return string.Empty;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string ResolveClientUrl(this HttpRequest request, string url) {
            if (string.IsNullOrWhiteSpace(url)) return url;
            if (url.StartsWith("http:", StringComparison.OrdinalIgnoreCase)) { return url; }
            if (url.StartsWith("https:", StringComparison.OrdinalIgnoreCase)) { return url; }
            if (url.StartsWith("/", StringComparison.OrdinalIgnoreCase)) { return url; }
            if (url.StartsWith("~/", StringComparison.OrdinalIgnoreCase)) {
                return Path.Combine(request.ApplicationPath, url.Substring(2));
            }
            var basePath = request.GetBasePath();
            if (url.StartsWith("./", StringComparison.OrdinalIgnoreCase)) {
                url = url.Substring(2);
            }
            while (url.StartsWith("../", StringComparison.OrdinalIgnoreCase)) {
                url = url.Substring(3);
                basePath = GoUpFolder(basePath);
            }
            return basePath + "/" + url;
        }

        public static string GetBasePath(this HttpRequest request) {
            return GoUpFolder(request.FilePath);
        }
        static string GoUpFolder(string path) {
            if (string.IsNullOrWhiteSpace(path) || !path.Contains("/")
                || path == "/"
                ) throw new Exception(string.Format("无法回到上一级目录：【{0}】", path));
            var i = path.LastIndexOf("/", StringComparison.Ordinal);
            return path.Substring(0, i);
        }
        public static string GetRootUri(this Page page) {
            return page.Request.ApplicationPath;
        }
        public static string GetRootUri(this HttpRequest request) {
            return request.ApplicationPath;
        }
        #region 上传文件相关
        /// <summary>
        /// 使用原始文件名保存
        /// </summary>
        /// <param name="file">上传文件</param>
        /// <param name="path">保存路径（不存在会自动创建）</param>
        /// <returns>成功返回保存路径，失败返回String.Empty</returns>
        public static string SaveToPath(this HttpPostedFileBase file, string path) {
            string fileName = System.IO.Path.GetFileName(file.FileName);
            if (System.IO.Directory.Exists(path) == false) {
                try {
                    System.IO.Directory.CreateDirectory(path);
                } catch {
                    return string.Empty;
                }
            }
            string toF = System.IO.Path.Combine(path, fileName);
            try {
                file.SaveAs(toF);
            } catch {
                return string.Empty;
            }
            return toF;
        }
        /// <summary>
        /// 使用原始文件名保存
        /// </summary>
        /// <param name="file">上传文件</param>
        /// <param name="path">保存路径（不存在会自动创建）</param>
        /// <returns>成功返回保存路径，失败返回String.Empty</returns>
        public static string SaveToPath(this HttpPostedFile file, string path) {
            string fileName = System.IO.Path.GetFileName(file.FileName);
            if (System.IO.Directory.Exists(path) == false) {
                try {
                    System.IO.Directory.CreateDirectory(path);
                } catch {
                    return string.Empty;
                }
            }
            string toF = System.IO.Path.Combine(path, fileName);
            try {
                file.SaveAs(toF);
            } catch {
                return string.Empty;
            }
            return toF;
        }
        /// <summary>
        /// 使用随机名字保存
        /// </summary>
        /// <param name="file"></param>
        /// <param name="path"></param>
        /// <returns>成功返回保存路径，失败返回String.Empty</returns>
        public static string SaveByRandomName(this HttpPostedFileBase file, string path) {
            string ext = System.IO.Path.GetExtension(file.FileName);
            string toPath = System.IO.Path.Combine(path, DateTime.Now.ToString("yyyy\\\\MM-dd"));
            if (System.IO.Directory.Exists(toPath) == false) {
                try {
                    System.IO.Directory.CreateDirectory(toPath);
                } catch {
                    return string.Empty;
                }
            }
            string toF = System.IO.Path.Combine(toPath, string.Format("{0}{1}", Guid.NewGuid(), ext));
            try {
                file.SaveAs(toF);
            } catch {
                return string.Empty;
            }
            return toF;
        }
        /// <summary>
        /// 使用随机名字保存
        /// </summary>
        /// <param name="file"></param>
        /// <param name="path"></param>
        /// <returns>成功返回保存路径，失败返回String.Empty</returns>
        public static string SaveByRandomName(this HttpPostedFile file, string path) {
            string ext = System.IO.Path.GetExtension(file.FileName);
            string toPath = System.IO.Path.Combine(path, DateTime.Now.ToString("yyyy\\\\MM-dd"));
            if (System.IO.Directory.Exists(toPath) == false) {
                try {
                    System.IO.Directory.CreateDirectory(toPath);
                } catch {
                    return string.Empty;
                }
            }
            string toF = System.IO.Path.Combine(toPath, string.Format("{0}{1}", Guid.NewGuid(), ext));
            try {
                file.SaveAs(toF);
            } catch {
                return string.Empty;
            }
            return toF;
        }
        #endregion

        #region Page
        public static void Redirect(this System.Web.UI.Page thePage, string url) {
            thePage.Response.Redirect(url);
        }
        public static void Redirect(this System.Web.UI.Page thePage, string url, bool endResponse) {
            thePage.Response.Redirect(url, endResponse);
        }
        #endregion
    }
    /// <summary>
    /// 请求类型
    /// </summary>
    public enum HttpVerbs : int {
        GET = 0x01,
        POST = 0x02,
        Anyone = GET | POST
    }
}